<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2017/4/21
 * Time: 16:43
 */

namespace SDXApi\Service;


use SDXApi\Abstracts\TemplateAbstract;
use SDXApi\Listeners\LocationLinkSourceListener;
use SDXApi\Model\HomeTemplateStencilImageModel;

/**
 * Class HomeTemplateImageGroupService
 * @package SDXApi\Service
 */
class HomeTemplateImageGroupService extends TemplateAbstract
{
    /**
     * @var HomeTemplateStencilImageModel
     */
    protected $templateStencilImageModel;

    /**
     * HomeTemplateImageService constructor.
     */
    public function __construct()
    {
        $this->templateStencilImageModel = new HomeTemplateStencilImageModel();
    }

    /**
     * Created by Jerry
     * @param array $template
     * @param int $userId
     * @param int $wid
     * @return array|bool
     */
    public function handle($template = array(), $userId = 0, $wid = 8)
    {
        $source = $this->sourceApp();
        $version = I('post.version', 0);

        if (($source == 1 && $version <= 62) || ($source == 2 && $version == '2.3.59')) {
            return false;
        }

        $cacheName = 'home_template_image_group_id_' . $template['id'] . '_app_' . $source;

//		获取缓存
        $data = $this->getCache($cacheName);

        if (empty($data)) {
            $data = $this->stencilImageGroup($template, $userId, $wid);
            $this->cacheData($cacheName, $data, 3600);
        }

        return $data;
    }

    /**
     * Created by Jerry
     * @param array $template
     * @param int $userId
     * @param int $wid
     * @return array|bool
     */
    protected function stencilImageGroup($template = array(), $userId = 0, $wid = 8)
    {
        $images = $this->findTemplateStencilImageByStencilId($template['id']);

        if (empty($images)) {
            return false;
        }

        $locationLinkListener = new LocationLinkSourceListener();

        foreach ($images as $key => $value) {
            $link_data = $locationLinkListener->onCallLink($value['link']);
            if (! empty($link_data)) {
                $images[$key]['link_data'] = $link_data;
            }
        }

        $imageGroup = array_chunk($images, 3);

        $i = 0;
        $data = array();
        foreach ($imageGroup as $key => $value) {
            $i++;
            $rs = $i / 2;

            if (is_int($rs)) {
                $data[$key]['fluid'] = 2;
                $data[$key]['images'] = $value;
            }
            else{
                $data[$key]['fluid'] = 1;
                $data[$key]['images'] = $value;
            }

        }

        $template['group_list'] = $data;
        return $template;
    }

    /**
     * Created by Jerry
     * @param $stencilId
     * @return mixed
     */
    protected function findTemplateStencilImageByStencilId($stencilId)
    {
        return $this->templateStencilImageModel->find_template_stencil_images_group_by_stencil_id($stencilId);
    }
}